home *** CD-ROM | disk | FTP | other *** search
/ CU Amiga Super CD-ROM 22 / CU Amiga Magazine's Super CD-ROM 22 (1998)(EMAP Images)(GB)[!][issue 1998-05].iso / PowerPC / Archivers / ZLib / deflate.c < prev    next >
Encoding:
C/C++ Source or Header  |  1998-02-20  |  43.0 KB  |  1,168 lines

  1. /* deflate.c -- compress data using the deflation algorithm
  2.  * Copyright (C) 1995-1996 Jean-loup Gailly.
  3.  * For conditions of distribution and use, see copyright notice in zlib.h 
  4.  */
  5.  
  6. /*
  7.  *  ALGORITHM
  8.  *
  9.  *      The "deflation" process depends on being able to identify portions
  10.  *      of the input text which are identical to earlier input (within a
  11.  *      sliding window trailing behind the input currently being processed).
  12.  *
  13.  *      The most straightforward technique turns out to be the fastest for
  14.  *      most input files: try all possible matches and select the longest.
  15.  *      The key feature of this algorithm is that insertions into the string
  16.  *      dictionary are very simple and thus fast, and deletions are avoided
  17.  *      completely. Insertions are performed at each input character, whereas
  18.  *      string matches are performed only when the previous match ends. So it
  19.  *      is preferable to spend more time in matches to allow very fast string
  20.  *      insertions and avoid deletions. The matching algorithm for small
  21.  *      strings is inspired from that of Rabin & Karp. A brute force approach
  22.  *      is used to find longer strings when a small match has been found.
  23.  *      A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  24.  *      (by Leonid Broukhis).
  25.  *         A previous version of this file used a more sophisticated algorithm
  26.  *      (by Fiala and Greene) which is guaranteed to run in linear amortized
  27.  *      time, but has a larger average cost, uses more memory and is patented.
  28.  *      However the F&G algorithm may be faster for some highly redundant
  29.  *      files if the parameter max_chain_length (described below) is too large.
  30.  *
  31.  *  ACKNOWLEDGEMENTS
  32.  *
  33.  *      The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  34.  *      I found it in 'freeze' written by Leonid Broukhis.
  35.  *      Thanks to many people for bug reports and testing.
  36.  *
  37.  *  REFERENCES
  38.  *
  39.  *      Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  40.  *      Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  41.  *
  42.  *      A description of the Rabin and Karp algorithm is given in the book
  43.  *         "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  44.  *
  45.  *      Fiala,E.R., and Greene,D.H.
  46.  *         Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  47.  *
  48.  */
  49.  
  50. /* $Id: deflate.c,v 1.15 1996/07/24 13:40:58 me Exp $ */
  51.  
  52. #include "deflate.h"
  53.  
  54. char deflate_copyright[] = " deflate 1.0.4 Copyright 1995-1996 Jean-loup Gailly ";
  55. /*
  56.   If you use the zlib library in a product, an acknowledgment is welcome
  57.   in the documentation of your product. If for some reason you cannot
  58.   include such an acknowledgment, I would appreciate that you keep this
  59.   copyright string in the executable of your product.
  60.  */
  61.  
  62. /* ===========================================================================
  63.  *  Function prototypes.
  64.  */
  65. typedef enum {
  66.     need_more,      /* block not completed, need more input or more output */
  67.     block_done,     /* block flush performed */
  68.     finish_started, /* finish started, need only more output at next deflate */
  69.     finish_done     /* finish done, accept no more input or output */
  70. } block_state;
  71.  
  72. typedef block_state (*compress_func) OF((deflate_state *s, int flush));
  73. /* Compression function. Returns the block state after the call. */
  74.  
  75. local void fill_window    OF((deflate_state *s));
  76. local block_state deflate_stored OF((deflate_state *s, int flush));
  77. local block_state deflate_fast   OF((deflate_state *s, int flush));
  78. local block_state deflate_slow   OF((deflate_state *s, int flush));
  79. local void lm_init        OF((deflate_state *s));
  80. local uInt longest_match  OF((deflate_state *s, IPos cur_match));
  81. local void putShortMSB    OF((deflate_state *s, uInt b));
  82. local void flush_pending  OF((z_streamp strm));
  83. local int read_buf        OF((z_streamp strm, charf *buf, unsigned size));
  84. #ifdef ASMV
  85.       void match_init OF((void)); /* asm code initialization */
  86. #endif
  87.  
  88. #ifdef DEBUG
  89. local  void check_match OF((deflate_state *s, IPos start, IPos match,
  90.                             int length));
  91. #endif
  92.  
  93. /* ===========================================================================
  94.  * Local data
  95.  */
  96.  
  97. #define NIL 0
  98. /* Tail of hash chains */
  99.  
  100. #ifndef TOO_FAR
  101. #  define TOO_FAR 4096
  102. #endif
  103. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  104.  
  105. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  106. /* Minimum amount of lookahead, except at the end of the input file.
  107.  * See deflate.c for comments about the MIN_MATCH+1.
  108.  */
  109.  
  110. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  111.  * the desired pack level (0..9). The values given below have been tuned to
  112.  * exclude worst case performance for pathological files. Better values may be
  113.  * found for specific files.
  114.  */
  115. typedef struct config_s {
  116.    ush good_length; /* reduce lazy search above this match length */
  117.    ush max_lazy;    /* do not perform lazy search above this match length */
  118.    ush nice_length; /* quit search above this match length */
  119.    ush max_chain;
  120.    compress_func func;
  121. } config;
  122.  
  123. local config configuration_table[10] = {
  124. /*      good lazy nice chain */
  125. /* 0 */ {0,    0,  0,    0, deflate_stored},  /* store only */
  126. /* 1 */ {4,    4,  8,    4, deflate_fast}, /* maximum speed, no lazy matches */
  127. /* 2 */ {4,    5, 16,    8, deflate_fast},
  128. /* 3 */ {4,    6, 32,   32, deflate_fast},
  129.  
  130. /* 4 */ {4,    4, 16,   16, deflate_slow},  /* lazy matches */
  131. /* 5 */ {8,   16, 32,   32, deflate_slow},
  132. /* 6 */ {8,   16, 128, 128, deflate_slow},
  133. /* 7 */ {8,   32, 128, 256, deflate_slow},
  134. /* 8 */ {32, 128, 258, 1024, deflate_slow},
  135. /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* maximum compression */
  136.  
  137. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  138.  * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  139.  * meaning.
  140.  */
  141.  
  142. #define EQUAL 0
  143. /* result of memcmp for equal strings */
  144.  
  145. struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
  146.  
  147. /* ===========================================================================
  148.  * Update a hash value with the given input byte
  149.  * IN  assertion: all calls to to UPDATE_HASH are made with consecutive
  150.  *    input characters, so that a running hash key can be computed from the
  151.  *    previous key instead of complete recalculation each time.
  152.  */
  153. #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
  154.  
  155.  
  156. /* ===========================================================================
  157.  * Insert string str in the dictionary and set match_head to the previous head
  158.  * of the hash chain (the most recent string with same hash key). Return
  159.  * the previous length of the hash chain.
  160.  * IN  assertion: all calls to to INSERT_STRING are made with consecutive
  161.  *    input characters and the first MIN_MATCH bytes of str are valid
  162.  *    (except for the last MIN_MATCH-1 bytes of the input file).
  163.  */
  164. #define INSERT_STRING(s, str, match_head) \
  165.    (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  166.     s->prev[(str) & s->w_mask] = match_head = s->head[s->ins_h], \
  167.     s->head[s->ins_h] = (Pos)(str))
  168.  
  169. /* ===========================================================================
  170.  * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  171.  * prev[] will be initialized on the fly.
  172.  */
  173. #define CLEAR_HASH(s) \
  174.     s->head[s->hash_size-1] = NIL; \
  175.     zmemzero((charf *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
  176.  
  177. /* ========================================================================= */
  178. int deflateInit_(z_streamp strm, int level, const char *version, int stream_size)
  179. {
  180.     return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
  181.                          Z_DEFAULT_STRATEGY, version, stream_size);
  182.     /* To do: ignore strm->next_in if we use it as window */
  183. }
  184.  
  185. /* ========================================================================= */
  186. int deflateInit2_(z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy,
  187.                   const char *version, int stream_size)
  188. {
  189.     deflate_state *s;
  190.     int noheader = 0;
  191.  
  192.     ushf *overlay;
  193.     /* We overlay pending_buf and d_buf+l_buf. This works since the average
  194.      * output size for (length,distance) codes is <= 24 bits.
  195.      */
  196.  
  197.     if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  198.         stream_size != sizeof(z_stream)) {
  199.         return Z_VERSION_ERROR;
  200.     }
  201.     if (strm == Z_NULL) return Z_STREAM_ERROR;
  202.  
  203.     strm->msg = Z_NULL;
  204.     if (strm->zalloc == Z_NULL) {
  205.         strm->zalloc = zcalloc;
  206.         strm->opaque = (voidpf)0;
  207.     }
  208.     if (strm->zfree == Z_NULL) strm->zfree = zcfree;
  209.  
  210.     if (level == Z_DEFAULT_COMPRESSION) level = 6;
  211.  
  212.     if (windowBits < 0) { /* undocumented feature: suppress zlib header */
  213.         noheader = 1;
  214.         windowBits = -windowBits;
  215.     }
  216.     if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
  217.         windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  218.         strategy < 0 || strategy > Z_HUFFMAN_ONLY) {
  219.         return Z_STREAM_ERROR;
  220.     }
  221.     s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  222.     if (s == Z_NULL) return Z_MEM_ERROR;
  223.     strm->state = (struct internal_state FAR *)s;
  224.     s->strm = strm;
  225.  
  226.     s->noheader = noheader;
  227.     s->w_bits = windowBits;
  228.     s->w_size = 1 << s->w_bits;
  229.     s->w_mask = s->w_size - 1;
  230.  
  231.     s->hash_bits = memLevel + 7;
  232.     s->hash_size = 1 << s->hash_bits;
  233.     s->hash_mask = s->hash_size - 1;
  234.     s->hash_shift =  ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  235.  
  236.     s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  237.     s->prev   = (Posf *)  ZALLOC(strm, s->w_size, sizeof(Pos));
  238.     s->head   = (Posf *)  ZALLOC(strm, s->hash_size, sizeof(Pos));
  239.  
  240.     s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  241.  
  242.     overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  243.     s->pending_buf = (uchf *) overlay;
  244.  
  245.     if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  246.         s->pending_buf == Z_NULL) {
  247.         strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
  248.         deflateEnd (strm);
  249.         return Z_MEM_ERROR;
  250.     }
  251.     s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  252.     s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  253.  
  254.     s->level = level;
  255.     s->strategy = strategy;
  256.     s->method = (Byte)method;
  257.  
  258.     return deflateReset(strm);
  259. }
  260.  
  261. /* ========================================================================= */
  262. int deflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  263. {
  264.     deflate_state *s;
  265.     uInt length = dictLength;
  266.     uInt n;
  267.     IPos hash_head = 0;
  268.  
  269.     if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
  270.         strm->state->status != INIT_STATE) return Z_STREAM_ERROR;
  271.  
  272.     s = strm->state;
  273.     strm->adler = adler32(strm->adler, dictionary, dictLength);
  274.  
  275.     if (length < MIN_MATCH) return Z_OK;
  276.     if (length > MAX_DIST(s)) {
  277.         length = MAX_DIST(s);
  278.         dictionary += dictLength - length;
  279.     }
  280.     zmemcpy((charf *)s->window, dictionary, length);
  281.     s->strstart = length;
  282.     s->block_start = (long)length;
  283.  
  284.     /* Insert all strings in the hash table (except for the last two bytes).
  285.      * s->lookahead stays null, so s->ins_h will be recomputed at the next
  286.      * call of fill_window.
  287.      */
  288.     s->ins_h = s->window[0];
  289.     UPDATE_HASH(s, s->ins_h, s->window[1]);
  290.     for (n = 0; n <= length - MIN_MATCH; n++) {
  291.         INSERT_STRING(s, n, hash_head);
  292.     }
  293.     if (hash_head) hash_head = 0;  /* to make compiler happy */
  294.     return Z_OK;
  295. }
  296.  
  297. /* ========================================================================= */
  298. int deflateReset (z_streamp strm)
  299. {
  300.     deflate_state *s;
  301.     
  302.     if (strm == Z_NULL || strm->state == Z_NULL ||
  303.         strm->zalloc == Z_NULL || strm->zfree == Z_NULL) return Z_STREAM_ERROR;
  304.  
  305.     strm->total_in = strm->total_out = 0;
  306.     strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  307.     strm->data_type = Z_UNKNOWN;
  308.  
  309.     s = (deflate_state *)strm->state;
  310.     s->pending = 0;
  311.     s->pending_out = s->pending_buf;
  312.  
  313.     if (s->noheader < 0) {
  314.         s->noheader = 0; /* was set to -1 by deflate(..., Z_FINISH); */
  315.     }
  316.     s->status = s->noheader ? BUSY_STATE : INIT_STATE;
  317.     strm->adler = 1;
  318.     s->last_flush = Z_NO_FLUSH;
  319.  
  320.     _tr_init(s);
  321.     lm_init(s);
  322.  
  323.     return Z_OK;
  324. }
  325.  
  326. /* ========================================================================= */
  327. int deflateParams(z_streamp strm, int level, int strategy)
  328. {
  329.     deflate_state *s;
  330.     compress_func func;
  331.     int err = Z_OK;
  332.  
  333.     if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  334.     s = strm->state;
  335.  
  336.     if (level == Z_DEFAULT_COMPRESSION) {
  337.         level = 6;
  338.     }
  339.     if (level < 0 || level > 9 || strategy < 0 || strategy > Z_HUFFMAN_ONLY) {
  340.         return Z_STREAM_ERROR;
  341.     }
  342.     func = configuration_table[s->level].func;
  343.  
  344.     if (func != configuration_table[level].func && strm->total_in != 0) {
  345.         /* Flush the last buffer: */
  346.         err = deflate(strm, Z_PARTIAL_FLUSH);
  347.     }
  348.     if (s->level != level) {
  349.         s->level = level;
  350.         s->max_lazy_match   = configuration_table[level].max_lazy;
  351.         s->good_match       = configuration_table[level].good_length;
  352.         s->nice_match       = configuration_table[level].nice_length;
  353.         s->max_chain_length = configuration_table[level].max_chain;
  354.     }
  355.     s->strategy = strategy;
  356.     return err;
  357. }
  358.  
  359. /* =========================================================================
  360.  * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  361.  * IN assertion: the stream state is correct and there is enough room in
  362.  * pending_buf.
  363.  */
  364. local void putShortMSB (deflate_state *s, uInt b)
  365. {
  366.     put_byte(s, (Byte)(b >> 8));
  367.     put_byte(s, (Byte)(b & 0xff));
  368. }   
  369.  
  370. /* =========================================================================
  371.  * Flush as much pending output as possible. All deflate() output goes
  372.  * through this function so some applications may wish to modify it
  373.  * to avoid allocating a large strm->next_out buffer and copying into it.
  374.  * (See also read_buf()).
  375.  */
  376. local void flush_pending(z_streamp strm)
  377. {
  378.     unsigned len = strm->state->pending;
  379.  
  380.     if (len > strm->avail_out) len = strm->avail_out;
  381.     if (len == 0) return;
  382.  
  383.     zmemcpy(strm->next_out, strm->state->pending_out, len);
  384.     strm->next_out  += len;
  385.     strm->state->pending_out  += len;
  386.     strm->total_out += len;
  387.     strm->avail_out  -= len;
  388.     strm->state->pending -= len;
  389.     if (strm->state->pending == 0) {
  390.         strm->state->pending_out = strm->state->pending_buf;
  391.     }
  392. }
  393.  
  394. /* ========================================================================= */
  395. int deflate (z_streamp strm, int flush)
  396. {
  397.     int old_flush; /* value of flush param for previous deflate call */
  398.     deflate_state *s;
  399.  
  400.     if (strm == Z_NULL || strm->state == Z_NULL ||
  401.         flush > Z_FINISH || flush < 0) {
  402.         return Z_STREAM_ERROR;
  403.     }
  404.     s = strm->state;
  405.  
  406.     if (strm->next_out == Z_NULL ||
  407.         (strm->next_in == Z_NULL && strm->avail_in != 0) ||
  408.         (s->status == FINISH_STATE && flush != Z_FINISH)) {
  409.         ERR_RETURN(strm, Z_STREAM_ERROR);
  410.     }
  411.     if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  412.  
  413.     s->strm = strm; /* just in case */
  414.     old_flush = s->last_flush;
  415.     s->last_flush = flush;
  416.  
  417.     /* Write the zlib header */
  418.     if (s->status == INIT_STATE) {
  419.  
  420.         uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  421.         uInt level_flags = (s->level-1) >> 1;
  422.  
  423.         if (level_flags > 3) level_flags = 3;
  424.         header |= (level_flags << 6);
  425.         if (s->strstart != 0) header |= PRESET_DICT;
  426.         header += 31 - (header % 31);
  427.  
  428.         s->status = BUSY_STATE;
  429.         putShortMSB(s, header);
  430.  
  431.         /* Save the adler32 of the preset dictionary: */
  432.         if (s->strstart != 0) {
  433.             putShortMSB(s, (uInt)(strm->adler >> 16));
  434.             putShortMSB(s, (uInt)(strm->adler & 0xffff));
  435.         }
  436.         strm->adler = 1L;
  437.     }
  438.  
  439.     /* Flush as much pending output as possible */
  440.     if (s->pending != 0) {
  441.         flush_pending(strm);
  442.         if (strm->avail_out == 0) {
  443.             /* Since avail_out is 0, deflate will be called again with
  444.              * more output space, but possibly with both pending and
  445.              * avail_in equal to zero. There won't be anything to do,
  446.              * but this is not an error situation so make sure we
  447.              * return OK instead of BUF_ERROR at next call of deflate:
  448.              */
  449.             s->last_flush = -1;
  450.             return Z_OK;
  451.         }
  452.  
  453.     /* Make sure there is something to do and avoid duplicate consecutive
  454.      * flushes. For repeated and useless calls with Z_FINISH, we keep
  455.      * returning Z_STREAM_END instead of Z_BUFF_ERROR.
  456.      */
  457.     } else if (strm->avail_in == 0 && flush <= old_flush &&
  458.                flush != Z_FINISH) {
  459.         ERR_RETURN(strm, Z_BUF_ERROR);
  460.     }
  461.  
  462.     /* User must not provide more input after the first FINISH: */
  463.     if (s->status == FINISH_STATE && strm->avail_in != 0) {
  464.         ERR_RETURN(strm, Z_BUF_ERROR);
  465.     }
  466.  
  467.     /* Start a new block or continue the current one.
  468.      */
  469.     if (strm->avail_in != 0 || s->lookahead != 0 ||
  470.         (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  471.         block_state bstate;
  472.  
  473.         bstate = (*(configuration_table[s->level].func))(s, flush);
  474.  
  475.         if (bstate == finish_started || bstate == finish_done) {
  476.             s->status = FINISH_STATE;
  477.         }
  478.         if (bstate == need_more || bstate == finish_started) {
  479.             if (strm->avail_out == 0) {
  480.                 s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
  481.             }
  482.             return Z_OK;
  483.             /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  484.              * of deflate should use the same flush parameter to make sure
  485.              * that the flush is complete. So we don't have to output an
  486.              * empty block here, this will be done at next call. This also
  487.              * ensures that for a very small output buffer, we emit at most
  488.              * one empty block.
  489.              */
  490.         }
  491.         if (bstate == block_done) {
  492.             if (flush == Z_PARTIAL_FLUSH) {
  493.                 _tr_align(s);
  494.             } else { /* FULL_FLUSH or SYNC_FLUSH */
  495.                 _tr_stored_block(s, (char*)0, 0L, 0);
  496.                 /* For a full flush, this empty block will be recognized
  497.                  * as a special marker by inflate_sync().
  498.                  */
  499.                 if (flush == Z_FULL_FLUSH) {
  500.                     CLEAR_HASH(s);             /* forget history */
  501.                 }
  502.             }
  503.             flush_pending(strm);
  504.             if (strm->avail_out == 0) {
  505.               s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  506.               return Z_OK;
  507.             }
  508.         }
  509.     }
  510.     Assert(strm->avail_out > 0, "bug2");
  511.  
  512.     if (flush != Z_FINISH) return Z_OK;
  513.     if (s->noheader) return Z_STREAM_END;
  514.  
  515.     /* Write the zlib trailer (adler32) */
  516.     putShortMSB(s, (uInt)(strm->adler >> 16));
  517.     putShortMSB(s, (uInt)(strm->adler & 0xffff));
  518.     flush_pending(strm);
  519.     /* If avail_out is zero, the application will call deflate again
  520.      * to flush the rest.
  521.      */
  522.     s->noheader = -1; /* write the trailer only once! */
  523.     return s->pending != 0 ? Z_OK : Z_STREAM_END;
  524. }
  525.  
  526. /* ========================================================================= */
  527. int deflateEnd (z_streamp strm)
  528. {
  529.     int status;
  530.  
  531.     if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  532.  
  533.     /* Deallocate in reverse order of allocations: */
  534.     TRY_FREE(strm, strm->state->pending_buf);
  535.     TRY_FREE(strm, strm->state->head);
  536.     TRY_FREE(strm, strm->state->prev);
  537.     TRY_FREE(strm, strm->state->window);
  538.  
  539.     status = strm->state->status;
  540.     ZFREE(strm, strm->state);
  541.     strm->state = Z_NULL;
  542.  
  543.     return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  544. }
  545.  
  546. /* ========================================================================= */
  547. int deflateCopy (z_streamp dest, z_streamp source)
  548. {
  549.     if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
  550.         return Z_STREAM_ERROR;
  551.     }
  552.     *dest = *source;
  553.     return Z_STREAM_ERROR; /* to be implemented */
  554. #if 0
  555.     dest->state = (struct internal_state FAR *)
  556.         (*dest->zalloc)(1, sizeof(deflate_state));
  557.     if (dest->state == Z_NULL) return Z_MEM_ERROR;
  558.  
  559.     *(dest->state) = *(source->state);
  560.     return Z_OK;
  561. #endif
  562. }
  563.  
  564. /* ===========================================================================
  565.  * Read a new buffer from the current input stream, update the adler32
  566.  * and total number of bytes read.  All deflate() input goes through
  567.  * this function so some applications may wish to modify it to avoid
  568.  * allocating a large strm->next_in buffer and copying from it.
  569.  * (See also flush_pending()).
  570.  */
  571. local int read_buf(z_streamp strm, charf *buf, unsigned size)
  572. {
  573.     unsigned len = strm->avail_in;
  574.  
  575.     if (len > size) len = size;
  576.     if (len == 0) return 0;
  577.  
  578.     strm->avail_in  -= len;
  579.  
  580.     if (!strm->state->noheader) {
  581.         strm->adler = adler32(strm->adler, strm->next_in, len);
  582.     }
  583.     zmemcpy(buf, strm->next_in, len);
  584.     strm->next_in  += len;
  585.     strm->total_in += len;
  586.  
  587.     return (int)len;
  588. }
  589.  
  590. /* ===========================================================================
  591.  * Initialize the "longest match" routines for a new zlib stream
  592.  */
  593. local void lm_init (deflate_state *s)
  594. {
  595.     s->window_size = (ulg)2L*s->w_size;
  596.  
  597.     CLEAR_HASH(s);
  598.  
  599.     /* Set the default configuration parameters:
  600.      */
  601.     s->max_lazy_match   = configuration_table[s->level].max_lazy;
  602.     s->good_match       = configuration_table[s->level].good_length;
  603.     s->nice_match       = configuration_table[s->level].nice_length;
  604.     s->max_chain_length = configuration_table[s->level].max_chain;
  605.  
  606.     s->strstart = 0;
  607.     s->block_start = 0L;
  608.     s->lookahead = 0;
  609.     s->match_length = s->prev_length = MIN_MATCH-1;
  610.     s->match_available = 0;
  611.     s->ins_h = 0;
  612. #ifdef ASMV
  613.     match_init(); /* initialize the asm code */
  614. #endif
  615. }
  616.  
  617. /* ===========================================================================
  618.  * Set match_start to the longest match starting at the given string and
  619.  * return its length. Matches shorter or equal to prev_length are discarded,
  620.  * in which case the result is equal to prev_length and match_start is
  621.  * garbage.
  622.  * IN assertions: cur_match is the head of the hash chain for the current
  623.  *   string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  624.  * OUT assertion: the match length is not greater than s->lookahead.
  625.  */
  626. #ifndef ASMV
  627. /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
  628.  * match.S. The code will be functionally equivalent.
  629.  */
  630. local uInt longest_match(deflate_state *s, IPos cur_match)
  631. {
  632.     unsigned chain_length = s->max_chain_length;/* max hash chain length */
  633.     register Bytef *scan = s->window + s->strstart; /* current string */
  634.     register Bytef *match;                       /* matched string */
  635.     register int len;                           /* length of current match */
  636.     int best_len = s->prev_length;              /* best match length so far */
  637.     int nice_match = s->nice_match;             /* stop if match long enough */
  638.     IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
  639.         s->strstart - (IPos)MAX_DIST(s) : NIL;
  640.     /* Stop when cur_match becomes <= limit. To simplify the code,
  641.      * we prevent matches with the string of window index 0.
  642.      */
  643.     Posf *prev = s->prev;
  644.     uInt wmask = s->w_mask;
  645.  
  646. #ifdef UNALIGNED_OK
  647.     /* Compare two bytes at a time. Note: this is not always beneficial.
  648.      * Try with and without -DUNALIGNED_OK to check.
  649.      */
  650.     register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
  651.     register ush scan_start = *(ushf*)scan;
  652.     register ush scan_end   = *(ushf*)(scan+best_len-1);
  653. #else
  654.     register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  655.     register Byte scan_end1  = scan[best_len-1];
  656.     register Byte scan_end   = scan[best_len];
  657. #endif
  658.  
  659.     /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  660.      * It is easy to get rid of this optimization if necessary.
  661.      */
  662.     Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  663.  
  664.     /* Do not waste too much time if we already have a good match: */
  665.     if (s->prev_length >= s->good_match) {
  666.         chain_length >>= 2;
  667.     }
  668.     /* Do not look for matches beyond the end of the input. This is necessary
  669.      * to make deflate deterministic.
  670.      */
  671.     if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
  672.  
  673.     Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  674.  
  675.     do {
  676.         Assert(cur_match < s->strstart, "no future");
  677.         match = s->window + cur_match;
  678.  
  679.         /* Skip to next match if the match length cannot increase
  680.          * or if the match length is less than 2:
  681.          */
  682. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  683.         /* This code assumes sizeof(unsigned short) == 2. Do not use
  684.          * UNALIGNED_OK if your compiler uses a different size.
  685.          */
  686.         if (*(ushf*)(match+best_len-1) != scan_end ||
  687.             *(ushf*)match != scan_start) continue;
  688.  
  689.         /* It is not necessary to compare scan[2] and match[2] since they are
  690.          * always equal when the other bytes match, given that the hash keys
  691.          * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  692.          * strstart+3, +5, ... up to strstart+257. We check for insufficient
  693.          * lookahead only every 4th comparison; the 128th check will be made
  694.          * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  695.          * necessary to put more guard bytes at the end of the window, or
  696.          * to check more often for insufficient lookahead.
  697.          */
  698.         Assert(scan[2] == match[2], "scan[2]?");
  699.         scan++, match++;
  700.         do {
  701.         } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  702.                  *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  703.                  *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  704.                  *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  705.                  scan < strend);
  706.         /* The funny "do {}" generates better code on most compilers */
  707.  
  708.         /* Here, scan <= window+strstart+257 */
  709.         Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  710.         if (*scan == *match) scan++;
  711.  
  712.         len = (MAX_MATCH - 1) - (int)(strend-scan);
  713.         scan = strend - (MAX_MATCH-1);
  714.  
  715. #else /* UNALIGNED_OK */
  716.  
  717.         if (match[best_len]   != scan_end  ||
  718.             match[best_len-1] != scan_end1 ||
  719.             *match            != *scan     ||
  720.             *++match          != scan[1])      continue;
  721.  
  722.         /* The check at best_len-1 can be removed because it will be made
  723.          * again later. (This heuristic is not always a win.)
  724.          * It is not necessary to compare scan[2] and match[2] since they
  725.          * are always equal when the other bytes match, given that
  726.          * the hash keys are equal and that HASH_BITS >= 8.
  727.          */
  728.         scan += 2, match++;
  729.         Assert(*scan == *match, "match[2]?");
  730.  
  731.         /* We check for insufficient lookahead only every 8th comparison;
  732.          * the 256th check will be made at strstart+258.
  733.          */
  734.         do {
  735.         } while (*++scan == *++match && *++scan == *++match &&
  736.                  *++scan == *++match && *++scan == *++match &&
  737.                  *++scan == *++match && *++scan == *++match &&
  738.                  *++scan == *++match && *++scan == *++match &&
  739.                  scan < strend);
  740.  
  741.         Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  742.  
  743.         len = MAX_MATCH - (int)(strend - scan);
  744.         scan = strend - MAX_MATCH;
  745.  
  746. #endif /* UNALIGNED_OK */
  747.  
  748.         if (len > best_len) {
  749.             s->match_start = cur_match;
  750.             best_len = len;
  751.             if (len >= nice_match) break;
  752. #ifdef UNALIGNED_OK
  753.             scan_end = *(ushf*)(scan+best_len-1);
  754. #else
  755.             scan_end1  = scan[best_len-1];
  756.             scan_end   = scan[best_len];
  757. #endif
  758.         }
  759.     } while ((cur_match = prev[cur_match & wmask]) > limit
  760.              && --chain_length != 0);
  761.  
  762.     if ((uInt)best_len <= s->lookahead) return best_len;
  763.     return s->lookahead;
  764. }
  765. #endif /* ASMV */
  766.  
  767. #ifdef DEBUG
  768. /* ===========================================================================
  769.  * Check that the match at match_start is indeed a match.
  770.  */
  771. local void check_match(s, start, match, length)
  772.     deflate_state *s;
  773.     IPos start, match;
  774.     int length;
  775. {
  776.     /* check that the match is indeed a match */
  777.     if (zmemcmp((charf *)s->window + match,
  778.                 (charf *)s->window + start, length) != EQUAL) {
  779.         fprintf(stderr, " start %u, match %u, length %d\n",
  780.                 start, match, length);
  781.         do {
  782.             fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
  783.         } while (--length != 0);
  784.         z_error("invalid match");
  785.     }
  786.     if (verbose > 1) {
  787.         fprintf(stderr,"\\[%d,%d]", start-match, length);
  788.         do { putc(s->window[start++], stderr); } while (--length != 0);
  789.     }
  790. }
  791. #else
  792. #  define check_match(s, start, match, length)
  793. #endif
  794.  
  795. /* ===========================================================================
  796.  * Fill the window when the lookahead becomes insufficient.
  797.  * Updates strstart and lookahead.
  798.  *
  799.  * IN assertion: lookahead < MIN_LOOKAHEAD
  800.  * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  801.  *    At least one byte has been read, or avail_in == 0; reads are
  802.  *    performed for at least two bytes (required for the zip translate_eol
  803.  *    option -- not supported here).
  804.  */
  805. local void fill_window(deflate_state *s)
  806. {
  807.     register unsigned n, m;
  808.     register Posf *p;
  809.     unsigned more;    /* Amount of free space at the end of the window. */
  810.     uInt wsize = s->w_size;
  811.  
  812.     do {
  813.         more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
  814.  
  815.         /* Deal with !@#$% 64K limit: */
  816.         if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  817.             more = wsize;
  818.  
  819.         } else if (more == (unsigned)(-1)) {
  820.             /* Very unlikely, but possible on 16 bit machine if strstart == 0
  821.              * and lookahead == 1 (input done one byte at time)
  822.              */
  823.             more--;
  824.  
  825.         /* If the window is almost full and there is insufficient lookahead,
  826.          * move the upper half to the lower one to make room in the upper half.
  827.          */
  828.         } else if (s->strstart >= wsize+MAX_DIST(s)) {
  829.  
  830.             zmemcpy((charf *)s->window, (charf *)s->window+wsize,
  831.                    (unsigned)wsize);
  832.             s->match_start -= wsize;
  833.             s->strstart    -= wsize; /* we now have strstart >= MAX_DIST */
  834.  
  835.             s->block_start -= (long) wsize;
  836.  
  837.             /* Slide the hash table (could be avoided with 32 bit values
  838.                at the expense of memory usage):
  839.              */
  840.             n = s->hash_size;
  841.             p = &s->head[n];
  842.             do {
  843.                 m = *--p;
  844.                 *p = (Pos)(m >= wsize ? m-wsize : NIL);
  845.             } while (--n);
  846.  
  847.             n = wsize;
  848.             p = &s->prev[n];
  849.             do {
  850.                 m = *--p;
  851.                 *p = (Pos)(m >= wsize ? m-wsize : NIL);
  852.                 /* If n is not on any hash chain, prev[n] is garbage but
  853.                  * its value will never be used.
  854.                  */
  855.             } while (--n);
  856.  
  857.             more += wsize;
  858.         }
  859.         if (s->strm->avail_in == 0) return;
  860.  
  861.         /* If there was no sliding:
  862.          *    strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  863.          *    more == window_size - lookahead - strstart
  864.          * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  865.          * => more >= window_size - 2*WSIZE + 2
  866.          * In the BIG_MEM or MMAP case (not yet supported),
  867.          *   window_size == input_size + MIN_LOOKAHEAD  &&
  868.          *   strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  869.          * Otherwise, window_size == 2*WSIZE so more >= 2.
  870.          * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  871.          */
  872.         Assert(more >= 2, "more < 2");
  873.  
  874.         n = read_buf(s->strm, (charf *)s->window + s->strstart + s->lookahead,
  875.                      more);
  876.         s->lookahead += n;
  877.  
  878.         /* Initialize the hash value now that we have some input: */
  879.         if (s->lookahead >= MIN_MATCH) {
  880.             s->ins_h = s->window[s->strstart];
  881.             UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  882. #if MIN_MATCH != 3
  883.             Call UPDATE_HASH() MIN_MATCH-3 more times
  884. #endif
  885.         }
  886.         /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  887.          * but this is not important since only literal bytes will be emitted.
  888.          */
  889.  
  890.     } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  891. }
  892.  
  893. /* ===========================================================================
  894.  * Flush the current block, with given end-of-file flag.
  895.  * IN assertion: strstart is set to the end of the current match.
  896.  */
  897. #define FLUSH_BLOCK_ONLY(s, eof) { \
  898.    _tr_flush_block(s, (s->block_start >= 0L ? \
  899.                    (charf *)&s->window[(unsigned)s->block_start] : \
  900.                    (charf *)Z_NULL), \
  901.                 (ulg)((long)s->strstart - s->block_start), \
  902.                 (eof)); \
  903.    s->block_start = s->strstart; \
  904.    flush_pending(s->strm); \
  905.    Tracev((stderr,"[FLUSH]")); \
  906. }
  907.  
  908. /* Same but force premature exit if necessary. */
  909. #define FLUSH_BLOCK(s, eof) { \
  910.    FLUSH_BLOCK_ONLY(s, eof); \
  911.    if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
  912. }
  913.  
  914. /* ===========================================================================
  915.  * Copy without compression as much as possible from the input stream, return
  916.  * the current block state.
  917.  * This function does not insert new strings in the dictionary since
  918.  * uncompressible data is probably not useful. This function is used
  919.  * only for the level=0 compression option.
  920.  * NOTE: this function should be optimized to avoid extra copying.
  921.  */
  922. local block_state deflate_stored(deflate_state *s, int flush)
  923. {
  924.     for (;;) {
  925.         /* Fill the window as much as possible: */
  926.         if (s->lookahead <= 1) {
  927.  
  928.             Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  929.                    s->block_start >= (long)s->w_size, "slide too late");
  930.  
  931.             fill_window(s);
  932.             if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
  933.  
  934.             if (s->lookahead == 0) break; /* flush the current block */
  935.         }
  936.         Assert(s->block_start >= 0L, "block gone");
  937.  
  938.         s->strstart += s->lookahead;
  939.         s->lookahead = 0;
  940.  
  941.         /* Stored blocks are limited to 0xffff bytes: */
  942.         if (s->strstart == 0 || s->strstart > 0xfffe) {
  943.             /* strstart == 0 is possible when wraparound on 16-bit machine */
  944.             s->lookahead = s->strstart - 0xffff;
  945.             s->strstart = 0xffff;
  946.         }
  947.  
  948.         /* Emit a stored block if it is large enough: */
  949.         if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
  950.             FLUSH_BLOCK(s, 0);
  951.         }
  952.     }
  953.     FLUSH_BLOCK(s, flush == Z_FINISH);
  954.     return flush == Z_FINISH ? finish_done : block_done;
  955. }
  956.  
  957. /* ===========================================================================
  958.  * Compress as much as possible from the input stream, return the current
  959.  * block state.
  960.  * This function does not perform lazy evaluation of matches and inserts
  961.  * new strings in the dictionary only for unmatched strings or for short
  962.  * matches. It is used only for the fast compression options.
  963.  */
  964. local block_state deflate_fast(deflate_state *s, int flush)
  965. {
  966.     IPos hash_head = NIL; /* head of the hash chain */
  967.     int bflush;           /* set if current block must be flushed */
  968.  
  969.     for (;;) {
  970.         /* Make sure that we always have enough lookahead, except
  971.          * at the end of the input file. We need MAX_MATCH bytes
  972.          * for the next match, plus MIN_MATCH bytes to insert the
  973.          * string following the next match.
  974.          */
  975.         if (s->lookahead < MIN_LOOKAHEAD) {
  976.             fill_window(s);
  977.             if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  978.                 return need_more;
  979.             }
  980.             if (s->lookahead == 0) break; /* flush the current block */
  981.         }
  982.  
  983.         /* Insert the string window[strstart .. strstart+2] in the
  984.          * dictionary, and set hash_head to the head of the hash chain:
  985.          */
  986.         if (s->lookahead >= MIN_MATCH) {
  987.             INSERT_STRING(s, s->strstart, hash_head);
  988.         }
  989.  
  990.         /* Find the longest match, discarding those <= prev_length.
  991.          * At this point we have always match_length < MIN_MATCH
  992.          */
  993.         if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  994.             /* To simplify the code, we prevent matches with the string
  995.              * of window index 0 (in particular we have to avoid a match
  996.              * of the string with itself at the start of the input file).
  997.              */
  998.             if (s->strategy != Z_HUFFMAN_ONLY) {
  999.                 s->match_length = longest_match (s, hash_head);
  1000.             }
  1001.             /* longest_match() sets match_start */
  1002.         }
  1003.         if (s->match_length >= MIN_MATCH) {
  1004.             check_match(s, s->strstart, s->match_start, s->match_length);
  1005.  
  1006.             bflush = _tr_tally(s, s->strstart - s->match_start,
  1007.                                s->match_length - MIN_MATCH);
  1008.  
  1009.             s->lookahead -= s->match_length;
  1010.  
  1011.             /* Insert new strings in the hash table only if the match length
  1012.              * is not too large. This saves time but degrades compression.
  1013.              */
  1014.             if (s->match_length <= s->max_insert_length &&
  1015.                 s->lookahead >= MIN_MATCH) {
  1016.                 s->match_length--; /* string at strstart already in hash table */
  1017.                 do {
  1018.                     s->strstart++;
  1019.                     INSERT_STRING(s, s->strstart, hash_head);
  1020.                     /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  1021.                      * always MIN_MATCH bytes ahead.
  1022.                      */
  1023.                 } while (--s->match_length != 0);
  1024.                 s->strstart++; 
  1025.             } else {
  1026.                 s->strstart += s->match_length;
  1027.                 s->match_length = 0;
  1028.                 s->ins_h = s->window[s->strstart];
  1029.                 UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  1030. #if MIN_MATCH != 3
  1031.                 Call UPDATE_HASH() MIN_MATCH-3 more times
  1032. #endif
  1033.                 /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  1034.                  * matter since it will be recomputed at next deflate call.
  1035.                  */
  1036.             }
  1037.         } else {
  1038.             /* No match, output a literal byte */
  1039.             Tracevv((stderr,"%c", s->window[s->strstart]));
  1040.             bflush = _tr_tally (s, 0, s->window[s->strstart]);
  1041.             s->lookahead--;
  1042.             s->strstart++; 
  1043.         }
  1044.         if (bflush) FLUSH_BLOCK(s, 0);
  1045.     }
  1046.     FLUSH_BLOCK(s, flush == Z_FINISH);
  1047.     return flush == Z_FINISH ? finish_done : block_done;
  1048. }
  1049.  
  1050. /* ===========================================================================
  1051.  * Same as above, but achieves better compression. We use a lazy
  1052.  * evaluation for matches: a match is finally adopted only if there is
  1053.  * no better match at the next window position.
  1054.  */
  1055. local block_state deflate_slow(deflate_state *s, int flush)
  1056. {
  1057.     IPos hash_head = NIL;    /* head of hash chain */
  1058.     int bflush;              /* set if current block must be flushed */
  1059.  
  1060.     /* Process the input block. */
  1061.     for (;;) {
  1062.         /* Make sure that we always have enough lookahead, except
  1063.          * at the end of the input file. We need MAX_MATCH bytes
  1064.          * for the next match, plus MIN_MATCH bytes to insert the
  1065.          * string following the next match.
  1066.          */
  1067.         if (s->lookahead < MIN_LOOKAHEAD) {
  1068.             fill_window(s);
  1069.             if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  1070.                 return need_more;
  1071.             }
  1072.             if (s->lookahead == 0) break; /* flush the current block */
  1073.         }
  1074.  
  1075.         /* Insert the string window[strstart .. strstart+2] in the
  1076.          * dictionary, and set hash_head to the head of the hash chain:
  1077.          */
  1078.         if (s->lookahead >= MIN_MATCH) {
  1079.             INSERT_STRING(s, s->strstart, hash_head);
  1080.         }
  1081.  
  1082.         /* Find the longest match, discarding those <= prev_length.
  1083.          */
  1084.         s->prev_length = s->match_length, s->prev_match = s->match_start;
  1085.         s->match_length = MIN_MATCH-1;
  1086.  
  1087.         if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  1088.             s->strstart - hash_head <= MAX_DIST(s)) {
  1089.             /* To simplify the code, we prevent matches with the string
  1090.              * of window index 0 (in particular we have to avoid a match
  1091.              * of the string with itself at the start of the input file).
  1092.              */
  1093.             if (s->strategy != Z_HUFFMAN_ONLY) {
  1094.                 s->match_length = longest_match (s, hash_head);
  1095.             }
  1096.             /* longest_match() sets match_start */
  1097.  
  1098.             if (s->match_length <= 5 && (s->strategy == Z_FILTERED ||
  1099.                  (s->match_length == MIN_MATCH &&
  1100.                   s->strstart - s->match_start > TOO_FAR))) {
  1101.  
  1102.                 /* If prev_match is also MIN_MATCH, match_start is garbage
  1103.                  * but we will ignore the current match anyway.
  1104.                  */
  1105.                 s->match_length = MIN_MATCH-1;
  1106.             }
  1107.         }
  1108.         /* If there was a match at the previous step and the current
  1109.          * match is not better, output the previous match:
  1110.          */
  1111.         if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  1112.             uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
  1113.             /* Do not insert strings in hash table beyond this. */
  1114.  
  1115.             check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  1116.  
  1117.             bflush = _tr_tally(s, s->strstart -1 - s->prev_match,
  1118.                                s->prev_length - MIN_MATCH);
  1119.  
  1120.             /* Insert in hash table all strings up to the end of the match.
  1121.              * strstart-1 and strstart are already inserted. If there is not
  1122.              * enough lookahead, the last two strings are not inserted in
  1123.              * the hash table.
  1124.              */
  1125.             s->lookahead -= s->prev_length-1;
  1126.             s->prev_length -= 2;
  1127.             do {
  1128.                 if (++s->strstart <= max_insert) {
  1129.                     INSERT_STRING(s, s->strstart, hash_head);
  1130.                 }
  1131.             } while (--s->prev_length != 0);
  1132.             s->match_available = 0;
  1133.             s->match_length = MIN_MATCH-1;
  1134.             s->strstart++;
  1135.  
  1136.             if (bflush) FLUSH_BLOCK(s, 0);
  1137.  
  1138.         } else if (s->match_available) {
  1139.             /* If there was no match at the previous position, output a
  1140.              * single literal. If there was a match but the current match
  1141.              * is longer, truncate the previous match to a single literal.
  1142.              */
  1143.             Tracevv((stderr,"%c", s->window[s->strstart-1]));
  1144.             if (_tr_tally (s, 0, s->window[s->strstart-1])) {
  1145.                 FLUSH_BLOCK_ONLY(s, 0);
  1146.             }
  1147.             s->strstart++;
  1148.             s->lookahead--;
  1149.             if (s->strm->avail_out == 0) return need_more;
  1150.         } else {
  1151.             /* There is no previous match to compare with, wait for
  1152.              * the next step to decide.
  1153.              */
  1154.             s->match_available = 1;
  1155.             s->strstart++;
  1156.             s->lookahead--;
  1157.         }
  1158.     }
  1159.     Assert (flush != Z_NO_FLUSH, "no flush?");
  1160.     if (s->match_available) {
  1161.         Tracevv((stderr,"%c", s->window[s->strstart-1]));
  1162.         _tr_tally (s, 0, s->window[s->strstart-1]);
  1163.         s->match_available = 0;
  1164.     }
  1165.     FLUSH_BLOCK(s, flush == Z_FINISH);
  1166.     return flush == Z_FINISH ? finish_done : block_done;
  1167. }
  1168.